package com.autorun.server.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.autorun.server.dto.ApiResponse;
import com.autorun.server.entity.Apk;
import com.autorun.server.service.ApkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * APK管理控制器
 * 
 * @author autorun
 * @version 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/apk")
public class ApkController {

    @Autowired
    private ApkService apkService;

    /**
     * 获取APK列表（分页）
     * 
     * @param game 游戏名称
     * @param page 页码
     * @param pageSize 页大小
     * @return APK分页数据
     */
    @GetMapping("/list")
    public ApiResponse<Map<String, Object>> getApkList(
            @RequestParam(required = false) String game,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(name = "page_size", defaultValue = "10") int pageSize) {
        try {
            Page<Apk> apkPage = apkService.getApkList(game, page, pageSize);
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", apkPage.getRecords());
            result.put("total", apkPage.getTotal());
            result.put("page", apkPage.getCurrent());
            result.put("pageSize", apkPage.getSize());
            result.put("totalPages", apkPage.getPages());
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取APK列表失败: {}", e.getMessage(), e);
            return ApiResponse.error("获取APK列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取APK详情
     * 
     * @param id APK ID
     * @return APK信息
     */
    @GetMapping("/{id}")
    public ApiResponse<Apk> getApkById(@PathVariable Integer id) {
        try {
            Apk apk = apkService.getApkById(id);
            return ApiResponse.success(apk);
        } catch (Exception e) {
            log.error("获取APK详情失败: {}", e.getMessage(), e);
            return ApiResponse.error("获取APK详情失败: " + e.getMessage());
        }
    }

    /**
     * 上传APK文件
     * 
     * @param file 上传的文件
     * @param name APK名称
     * @param game 游戏名称
     * @param versionCode 版本代码
     * @param description 描述
     * @return APK信息
     */
    @PostMapping("/upload")
    public ApiResponse<Apk> uploadApk(
            @RequestParam("file") MultipartFile file,
            @RequestParam("name") String name,
            @RequestParam("game") String game,
            @RequestParam("versionCode") Integer versionCode,
            @RequestParam(value = "description", required = false) String description) {
        try {
            if (file.isEmpty()) {
                return ApiResponse.error("请选择要上传的文件");
            }
            
            // TODO: 从认证中获取用户ID，这里暂时硬编码
            Integer uploadUserId = 1;
            
            Apk apk = apkService.uploadApk(file, name, game, versionCode, description, uploadUserId);
            return ApiResponse.success("上传APK成功", apk);
        } catch (Exception e) {
            log.error("上传APK失败: {}", e.getMessage(), e);
            return ApiResponse.error("上传APK失败: " + e.getMessage());
        }
    }

    /**
     * 更新APK信息
     * 
     * @param id APK ID
     * @param requestBody 请求体
     * @return APK信息
     */
    @PutMapping("/{id}")
    public ApiResponse<Apk> updateApk(@PathVariable Integer id, @RequestBody Map<String, Object> requestBody) {
        try {
            String name = (String) requestBody.get("name");
            String description = (String) requestBody.get("description");
            
            Apk apk = apkService.updateApk(id, name, description);
            return ApiResponse.success("更新APK成功", apk);
        } catch (Exception e) {
            log.error("更新APK失败: {}", e.getMessage(), e);
            return ApiResponse.error("更新APK失败: " + e.getMessage());
        }
    }

    /**
     * 切换APK状态
     * 
     * @param id APK ID
     * @return APK信息
     */
    @PostMapping("/{id}/toggle")
    public ApiResponse<Apk> toggleApkStatus(@PathVariable Integer id) {
        try {
            // 获取当前APK状态并切换
            Apk currentApk = apkService.getApkById(id);
            Boolean newStatus = !currentApk.getIsActive();
            
            Apk apk = apkService.toggleApkStatus(id, newStatus);
            return ApiResponse.success("切换APK状态成功", apk);
        } catch (Exception e) {
            log.error("切换APK状态失败: {}", e.getMessage(), e);
            return ApiResponse.error("切换APK状态失败: " + e.getMessage());
        }
    }

    /**
     * 删除APK
     * 
     * @param id APK ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteApk(@PathVariable Integer id) {
        try {
            apkService.deleteApk(id);
            return ApiResponse.success("删除APK成功");
        } catch (Exception e) {
            log.error("删除APK失败: {}", e.getMessage(), e);
            return ApiResponse.error("删除APK失败: " + e.getMessage());
        }
    }


}